package com.kevis.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {
    @Value("${sso.server.url}")
    private String ssoServer;

    /*** 无需登录就可访问*/
    @ResponseBody
    @GetMapping(value = "/hello")
    public String hello(HttpServletRequest request) {
        System.out.println(request.getRequestURI());
        System.out.println(request.getRequestURL());
        return "hello";
    }

    @GetMapping(value = "/employees") // a系统
    public String employees(Model model, HttpSession session
            , @RequestParam(value = "token", required = false) String token) {
        if (StringUtils.hasLength(token)) {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userinfo?token=" + token, String.class);
            String body = forEntity.getBody();

            session.setAttribute("loginUser", body);
        }
        Object loginUser = session.getAttribute("loginUser");

        if (loginUser == null) {
            return "redirect:" + ssoServer + "?url=http://client1.com:8081/employees";
        } else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "employees";
        }
    }

    @GetMapping(value = "/boos") // a系统
    public String boos(Model model, HttpSession session
            , @RequestParam(value = "token", required = false) String token) {
        if (StringUtils.hasLength(token)) {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userinfo?token=" + token, String.class);
            String body = forEntity.getBody();

            session.setAttribute("loginUser", body);
        }
        Object loginUser = session.getAttribute("loginUser");

        if (loginUser == null) {
            return "redirect:" + ssoServer + "?url=http://client2.com:8082/boos";
        } else {
            List<String> emps = new ArrayList<>();
            emps.add("张总");
            emps.add("李总");
            model.addAttribute("emps", emps);
            return "employees";
        }
    }

}
